const fs = require('fs');

//该方法用于找到一个js文件下的所有的非index.js的js文件
function findFiles(path='./controllers'){
    const files = fs.readdirSync(path);
    return files.filter(e=>e.endsWith('.js') && e !== 'index.js');
}

//注册所有路由
function registerRouter(files,router){
    files.forEach(fileName => {
        let md = require('../controllers/'+fileName);
        for(let mdInfo in md){
            let infoArr = mdInfo.split(" ");
            let method = infoArr[0];
            let url = infoArr[1];
            console.log('注册'+mdInfo);
            router[method](url,md[mdInfo]);
        }
    });
}

//生成token
function gengerToken(id,username){
    let time = +new Date();
    let tokenStr = time + "&" + username + "&" + id;
    return Buffer.from(tokenStr).toString('base64');
}

//解析token
function resolveToken(token){
    let str = Buffer.from(token,'base64').toString();
    let arr = str.split("&");
    return {
        timeStamp:arr[0],
        username:arr[1],
        id:arr[2]
    }
}

module.exports = {
    findFiles,registerRouter,resolveToken,gengerToken
}